# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0

import os
import re
import logging

from agent.plugin.common import writeFile, readFile
from agent.domain.base import BaseDomain

logger = logging.getLogger('common')


def getActiveOption(options, dosplit = True):
    m = re.match(r'.*\[([^\]]+)\].*', options)
    if m:
        return m.group(1)
    if dosplit:
        return options.split()[0]
    return options


class Vm(BaseDomain):
    __domain__ = "vm"
    
    def __init__(self):
        super().__init__(domain_name = self.__domain__)

        # Transparent_hugepage is already set in kernel boot cmdline, ingoring value from profile
        cmdline = readFile("/proc/cmdline")
        if cmdline.find("transparent_hugepage=") > 0:
            raise Exception("Can not find transparent_hugepage in /proc/cmdline")
        
        # Transparent_hugepage file exits
        transparent_hugepage_path = "/sys/kernel/mm/transparent_hugepage/enabled"
        if not os.path.exists(transparent_hugepage_path):
            transparent_hugepage_path = "/sys/kernel/mm/redhat_transparent_hugepage/enabled"
        if not os.path.exists(transparent_hugepage_path):
            raise Exception("Can not find /sys/kernel/mm/*transparent_hugepage/enabled file")

        self.transparent_hugepage_path = transparent_hugepage_path

    def vaild_param(self, param_name):
        return param_name == "transparent_hugepages"
    
    def set_value(self, param_name:str, param_value):
        if param_name == "transparent_hugepages" and param_value in ["always", "never", "madvise"]:
            writeFile(self.transparent_hugepage_path, param_value)
    
    def get_value(self, param_name:str):
        if param_name == "transparent_hugepages":
            return getActiveOption(readFile(self.transparent_hugepage_path))